﻿using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Administration;
using System.Collections.Generic;
using WebPartPages = Microsoft.SharePoint.WebPartPages;

namespace Core.Foundation.WebParts.CrossSiteListView
{
    /// <summary>
    /// CrossSiteListView class to set properties getting it from Tool Pane.
    /// </summary>
    [ToolboxItemAttribute(false)]
    public class CrossSiteListView : WebPartPages.WebPart, IWebEditable
    {
        #region Properties
        /// <summary>
        /// SelectedSite
        /// </summary>
        [Personalizable(PersonalizationScope.Shared)]
        [WebBrowsable(false)]
        [System.ComponentModel.Category("Custom Configuration")]
        [WebDisplayName("Selected Site")]
        [WebDescription("Selected Site")]
        public string SelectedSite
        {
            get;
            set;
        }
        /// <summary>
        /// SelectedSubSite
        /// </summary>
        [Personalizable(PersonalizationScope.Shared)]
        [WebBrowsable(false)]
        [System.ComponentModel.Category("Custom Configuration")]
        [WebDisplayName("Selected SubSite")]
        [WebDescription("Selected SubSite")]
        public string SelectedSubSite
        {
            get;
            set;
        }
        /// <summary>
        /// SelectedList
        /// </summary>
        [Personalizable(PersonalizationScope.Shared)]
        [WebBrowsable(false)]
        [System.ComponentModel.Category("Custom Configuration")]
        [WebDisplayName("Selected List")]
        [WebDescription("Selected List")]
        public string SelectedList
        {
            get;
            set;
        }
        /// <summary>
        /// SelectedView
        /// </summary>
        [Personalizable(PersonalizationScope.Shared)]
        [WebBrowsable(false)]
        [System.ComponentModel.Category("Custom Configuration")]
        [WebDisplayName("Selected View")]
        [WebDescription("Selected View")]
        public string SelectedView
        {
            get;
            set;
        }
        /// <summary>
        /// Filter
        /// </summary>
        [Personalizable(PersonalizationScope.Shared)]
        [WebBrowsable(true)]
        [System.ComponentModel.Category("Custom Configuration")]
        [WebDisplayName("Filter")]
        [WebDescription("Filter for View")]
        public string Filter
        {
            get;
            set;
        }
        /// <summary>
        /// AutoRefreshInterval
        /// </summary>
        [Personalizable(PersonalizationScope.Shared)]
        [WebBrowsable(true)]
        [System.ComponentModel.Category("Configuration")]
        [WebDisplayName("Auto Refresh Interval in Seconds")]
        [WebDescription("Auto Refresh Interval in Seconds")]
        public string AutoRefreshInterval
        {
            get;
            set;
        }
        #endregion

        #region Constructors
        /// <summary>
        /// CrossSiteListView
        /// </summary>
        public CrossSiteListView()
        {
            this.ExportMode = WebPartExportMode.All;
            
            
        }
        #endregion

        #region Variables & Constants
        private const string _ascxPath = @"~/_CONTROLTEMPLATES/Core.Foundation.webparts/CrossSiteListView/CrossSiteListViewUserControl.ascx";
        #endregion

        #region Modify ToolPane Appearence
        /// <summary>
        /// WebPartPages.ToolPart[] GetToolParts()
        /// </summary>
        /// <returns></returns>
        public override WebPartPages.ToolPart[] GetToolParts()
        {
            WebPartPages.ToolPart[] toolparts = new WebPartPages.ToolPart[2];
            WebPartPages.CustomPropertyToolPart custom = new WebPartPages.CustomPropertyToolPart();
            custom.Expand("Custom Configuration");
            WebPartPages.WebPartToolPart wptp = new WebPartPages.WebPartToolPart();
            //wptp.Expand(WebPartPages.WebPartToolPart.Categories.Appearance);
            wptp.Hide(WebPartPages.WebPartToolPart.Properties.FrameState);
            wptp.Hide(WebPartPages.WebPartToolPart.Properties.FrameType);
            toolparts[0] = custom;
            toolparts[1] = wptp;

            return toolparts;
        }
        #endregion

        #region Other Methods
        /// <summary>
        /// IWebEditable.CreateEditorParts()
        /// </summary>
        /// <returns></returns>
        EditorPartCollection IWebEditable.CreateEditorParts()
        {
            List<EditorPart> editors = new List<EditorPart>();
            editors.Add(new CustomEditorPart(this.ID));

            return new EditorPartCollection(editors);
        }
        /// <summary>
        /// IWebEditable.WebBrowsableObject
        /// </summary>
        object IWebEditable.WebBrowsableObject
        {
            get
            {
                return this;
            }
        }

        
        /// <summary>
        /// CreateChildControls
        /// </summary>
        protected override void CreateChildControls()
        {
            try
            {
                CrossSiteListViewUserControl control = Page.LoadControl(_ascxPath) as CrossSiteListViewUserControl;
                if (!string.IsNullOrEmpty(SelectedSite) && !string.IsNullOrEmpty(SelectedSubSite)
                    && !string.IsNullOrEmpty(SelectedList) && !string.IsNullOrEmpty(SelectedView))
                {
                    control.SelectedSite = SelectedSite;
                    control.SelectedSubSite = SelectedSubSite;
                    control.SelectedList = SelectedList;
                    control.SelectedView = SelectedView;
                    control.AutoRefreshInterval = AutoRefreshInterval;

                    if (!string.IsNullOrEmpty(Filter))
                    {
                        control.Filter = Filter;
                    }
                    

                    Controls.Add(control);
                }
            }
            catch (Exception ex)
            {
                string msg = ex.Message;
                // Exception handler code goes here...
            }
        }
        #endregion
    }


    #region Create EditorPart Class to modify Webpart Tool Pane
    /// <summary>
    /// CustomEditorPart : EditorPart
    /// </summary>
    public class CustomEditorPart : EditorPart
    {
        private DropDownList ddlSiteCollection;
        private DropDownList ddlWeb;
        private DropDownList ddlList;
        private DropDownList ddlView;
        private Label lblSite;
        private Label lblWeb;
        private Label lblList;
        private Label lblView;
        private CrossSiteListView webPart;

        /// <summary>
        /// CustomEditorPart
        /// </summary>
        /// <param name="webPartID"></param>
        public CustomEditorPart(string webPartID)
        {
            this.ID = "CustomEditorPart" + webPartID;
            this.Title = "Cross Site List View";
        }
        /// <summary>
        /// CreateChildControls
        /// </summary>
        protected override void CreateChildControls()
        {
            webPart = WebPartToEdit as CrossSiteListView;

            #region Create SiteCollection Dropdown

            ddlSiteCollection = new DropDownList();
            ddlSiteCollection.ID = "ddlSite";
            ddlSiteCollection.AutoPostBack = true;
            ddlSiteCollection.Visible = true;
            ddlSiteCollection.SelectedIndexChanged += new EventHandler(OnddlSiteChange);

            lblSite = new Label();
            lblSite.Text = "Sites";
            TableCell tcLblSite = new TableCell();
            tcLblSite.VerticalAlign = VerticalAlign.Top;
            tcLblSite.Controls.Add(lblSite);
            TableCell tcSite = new TableCell();
            tcSite.Controls.Add(ddlSiteCollection);
            TableRow trSite = new TableRow();
            trSite.Controls.Add(tcLblSite);
            trSite.Controls.Add(tcSite);

            #endregion

            #region  Create SubSites Dropdown

            ddlWeb = new DropDownList();
            ddlWeb.ID = "ddlWeb";
            ddlWeb.AutoPostBack = true;
            ddlWeb.Visible = false;
            ddlWeb.SelectedIndexChanged += new EventHandler(OnddlWebChange);


            lblWeb = new Label();
            lblWeb.Text = "Sub Sites";
            lblWeb.Visible = false;

            TableCell tcLblWeb = new TableCell();
            tcLblWeb.VerticalAlign = VerticalAlign.Top;
            tcLblWeb.Controls.Add(lblWeb);
            TableCell tcWeb = new TableCell();
            tcWeb.Controls.Add(ddlWeb);

            TableRow trWeb = new TableRow();
            trWeb.Controls.Add(tcLblWeb);
            trWeb.Controls.Add(tcWeb);

            #endregion

            #region  Create List Dropdown

            ddlList = new DropDownList();
            ddlList.ID = "ddlList";
            ddlList.AutoPostBack = true;
            ddlList.Visible = false;
            ddlList.SelectedIndexChanged += new EventHandler(OnddlListChange);

            lblList = new Label();
            lblList.Text = "Lists";
            lblList.Visible = false;
            TableCell tcLblList = new TableCell();
            tcLblList.VerticalAlign = VerticalAlign.Top;
            tcLblList.Controls.Add(lblList);
            TableCell tcList = new TableCell();
            tcList.Controls.Add(ddlList);
            TableRow trList = new TableRow();
            trList.Controls.Add(tcLblList);
            trList.Controls.Add(tcList);
            #endregion

            #region  Create View Dropdown

            ddlView = new DropDownList();
            ddlView.ID = "ddlView";
            ddlView.Visible = false;


            lblView = new Label();
            lblView.Text = "Views";
            lblView.Visible = false;
            TableCell tcLblView = new TableCell();
            tcLblView.VerticalAlign = VerticalAlign.Top;
            tcLblView.Controls.Add(lblView);
            TableCell tcView = new TableCell();
            tcView.Controls.Add(ddlView);
            TableRow trView = new TableRow();
            trView.Controls.Add(tcLblView);
            trView.Controls.Add(tcView);
            #endregion

            #region  Add Controls to Page.

            Table MainTlb = new Table();
            MainTlb.Controls.Add(trSite);
            MainTlb.Controls.Add(trWeb);
            MainTlb.Controls.Add(trList);
            MainTlb.Controls.Add(trView);

            try
            {
                Controls.Add(MainTlb);
                base.CreateChildControls();
                PopulateSiteDropDown();
                PopulateOtherControls();

            }
            catch
            {
                // exception handler code goes here
            }
            #endregion

        }
        /// <summary>
        /// OnddlSiteChange
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnddlSiteChange(object sender, EventArgs e)
        {
            DropDownList ddlCurrent = sender as DropDownList;
            ControlVisibility(ddlCurrent);
            if (ddlCurrent.SelectedIndex != 0)
                PopulateWebDropDown(ddlCurrent.SelectedValue, string.Empty);
        }
        /// <summary>
        /// OnddlWebChange
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnddlWebChange(object sender, EventArgs e)
        {
            DropDownList ddlCurrent = sender as DropDownList;
            ControlVisibility(ddlCurrent);
            if (ddlCurrent.SelectedIndex != 0)
                PopulateListDropDown(ddlSiteCollection.SelectedValue, ddlCurrent.SelectedValue, string.Empty);
        }
        /// <summary>
        /// OnddlListChange
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnddlListChange(object sender, EventArgs e)
        {
            DropDownList ddlCurrent = sender as DropDownList;
            ControlVisibility(ddlCurrent);
            if (ddlCurrent.SelectedIndex != 0)
                PopulateViewDropDown(ddlSiteCollection.SelectedValue, ddlWeb.SelectedValue, ddlCurrent.SelectedValue, string.Empty);
        }
        /// <summary>
        /// ApplyChanges
        /// </summary>
        /// <returns></returns>
        public override bool ApplyChanges()
        {
            EnsureChildControls();
            if (webPart != null)
            {
                webPart.SelectedSite = ddlSiteCollection.SelectedValue;
                webPart.SelectedSubSite = ddlWeb.SelectedValue;
                webPart.SelectedList = ddlList.SelectedValue;
                webPart.SelectedView = ddlView.SelectedValue;
                
            }

            return true;
        }
        /// <summary>
        /// SyncChanges
        /// </summary>
        public override void SyncChanges()
        {
            EnsureChildControls();
            if (webPart != null)
            {
                ddlSiteCollection.SelectedValue = webPart.SelectedSite;
                ddlWeb.SelectedValue = webPart.SelectedSubSite;
                ddlList.SelectedValue = webPart.SelectedList;
                ddlView.SelectedValue = webPart.SelectedView;

            }
        }
        /// <summary>
        /// PopulateSiteDropDown
        /// </summary>
        private void PopulateSiteDropDown()
        {
            ddlSiteCollection.Items.Clear();
            ddlWeb.Items.Clear();
            ddlList.Items.Clear();
            ddlView.Items.Clear();
            SPSite CurrentSite = SPContext.Current.Site;
            SPWebApplication CurrentWebApplication = CurrentSite.WebApplication;
            foreach (SPSite osite in CurrentWebApplication.Sites)
            {
                ddlSiteCollection.Items.Add(osite.Url);
                osite.Dispose();
            }
            ddlSiteCollection.DataBind();
            ddlSiteCollection.Items.Insert(0, "Please Select Site");


        }
        /// <summary>
        /// PopulateWebDropDown
        /// </summary>
        /// <param name="SelectedSiteUrl"></param>
        /// <param name="SelectedWeb"></param>
        private void PopulateWebDropDown(string SelectedSiteUrl, string SelectedWeb)
        {
            ddlWeb.Items.Clear();
            ddlList.Items.Clear();
            ddlView.Items.Clear();
            using (SPSite osite = new SPSite(SelectedSiteUrl))
            {
                foreach (SPWeb oweb in osite.AllWebs)
                {
                    ddlWeb.Items.Add(new ListItem(oweb.Url, oweb.ServerRelativeUrl));
                    oweb.Dispose();
                }
                if (!string.IsNullOrEmpty(SelectedWeb))
                    ddlWeb.SelectedIndex = ddlWeb.Items.IndexOf(ddlWeb.Items.FindByValue(SelectedWeb));


                ddlWeb.DataBind();
                ddlWeb.Items.Insert(0, "Please Select SubSite");
            }

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="SelectedSiteUrl"></param>
        /// <param name="SelectedWebUrl"></param>
        /// <param name="SelectedList"></param>
        private void PopulateListDropDown(string SelectedSiteUrl, string SelectedWebUrl, string SelectedList)
        {
            ddlList.Items.Clear();
            ddlView.Items.Clear();

            using (SPSite site = new SPSite(SelectedSiteUrl))
            {
                using (SPWeb oWebsite = site.OpenWeb(SelectedWebUrl))
                {
                    foreach (SPList list in oWebsite.Lists)
                    {
                        ddlList.Items.Add(list.Title);
                    }
                    ddlList.DataBind();
                    if (!string.IsNullOrEmpty(SelectedList))
                        ddlList.SelectedIndex = ddlList.Items.IndexOf(ddlList.Items.FindByValue(SelectedList));
                    ddlList.Items.Insert(0, "Please Select List");

                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="SelectedSiteUrl"></param>
        /// <param name="SelectedWebUrl"></param>
        /// <param name="ListName"></param>
        /// <param name="SelectedView"></param>

        private void PopulateViewDropDown(string SelectedSiteUrl, string SelectedWebUrl, string ListName, string SelectedView)
        {
            ddlView.Items.Clear();
            using (SPSite site = new SPSite(SelectedSiteUrl))
            {
                using (SPWeb oWebsite = site.OpenWeb(SelectedWebUrl))
                {
                    SPList list = oWebsite.Lists[ListName];
                    foreach (SPView view in list.Views)
                    {
                        ddlView.Items.Add(view.Title);
                    }
                    if (!string.IsNullOrEmpty(SelectedView))
                        ddlView.SelectedIndex = ddlView.Items.IndexOf(ddlView.Items.FindByValue(SelectedView));
                    ddlView.DataBind();
                    ddlView.Items.Insert(0, "Please Select View");
                }

            }
        }
        /// <summary>
        /// PopulateOtherControls
        /// </summary>
        private void PopulateOtherControls()
        {

            if (!string.IsNullOrEmpty(webPart.SelectedSubSite))
            {
                PopulateWebDropDown(webPart.SelectedSite, webPart.SelectedSubSite);
                lblWeb.Visible = true;
                ddlWeb.Visible = true;
                if (!string.IsNullOrEmpty(webPart.SelectedList))
                {
                    PopulateListDropDown(webPart.SelectedSite, webPart.SelectedSubSite, webPart.SelectedList);
                    lblList.Visible = true;
                    ddlList.Visible = true;
                    if (!string.IsNullOrEmpty(webPart.SelectedView))
                    {
                        PopulateViewDropDown(webPart.SelectedSite, webPart.SelectedSubSite, webPart.SelectedList, webPart.SelectedView);
                        lblView.Visible = true;
                        ddlView.Visible = true;
                    }
                }
            }
        }
        /// <summary>
        /// ControlVisibility
        /// </summary>
        /// <param name="ddl"></param>
        private void ControlVisibility(DropDownList ddl)
        {
            switch (ddl.ID.ToLower())
            {
                case "ddlsite":
                    {
                        if (ddl.SelectedIndex != 0)
                        {
                            ddlWeb.Visible = true;
                            lblWeb.Visible = true;
                            ddlList.Visible = false;
                            lblList.Visible = false;
                            ddlView.Visible = false;
                            lblView.Visible = false;
                        }
                        else
                        {
                            lblWeb.Visible = false;
                            lblList.Visible = false;
                            ddlList.Visible = false;
                            ddlWeb.Visible = false;
                            ddlView.Visible = false;
                            lblView.Visible = false;
                        }
                        break;
                    }
                case "ddlweb":
                    {
                        if (ddl.SelectedIndex != 0)
                        {
                            ddlList.Visible = true;
                            lblList.Visible = true;
                            ddlView.Visible = false;
                            lblView.Visible = false;
                        }
                        else
                        {
                            ddlList.Visible = false;
                            lblList.Visible = false;
                            ddlView.Visible = false;
                            lblView.Visible = false;
                        }
                        break;
                    }
                case "ddllist":
                    {
                        if (ddl.SelectedIndex != 0)
                        {
                            ddlView.Visible = true;
                            lblView.Visible = true;
                        }
                        else
                        {
                            ddlView.Visible = false;
                            lblView.Visible = false;
                        }
                        break;
                    }
            }
        }

    }
    #endregion
}

